/*   
 * Copyright (c) 2011, TUgether, TU Braunschweig
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
 
 /**
 * @author Mohamed Karray <mohamed.karray@gmx.de>
 *
 */
 

package de.tu_bs.tugether.liferayunit.listeners;


import com.gargoylesoftware.htmlunit.html.DomChangeEvent;
import com.gargoylesoftware.htmlunit.html.DomChangeListener;
import com.gargoylesoftware.htmlunit.html.HtmlButton;
import com.gargoylesoftware.htmlunit.html.HtmlElement;
import com.gargoylesoftware.htmlunit.html.HtmlPage;
import com.gargoylesoftware.htmlunit.html.HtmlTextInput;

import de.tu_bs.tugether.liferayunit.exceptions.LiferayElementNotFoundException;

public class AddLiferayTabListener implements DomChangeListener {

	private String tabName;
	private HtmlPage page;
	private boolean isJobEnded = false;
	private boolean inputValueAdded = false;
	private HtmlElement navigation;

	public AddLiferayTabListener(String tabName, HtmlPage page) throws LiferayElementNotFoundException {
		this.page = page;
		this.tabName = tabName;

		this.navigation = page.getElementById("navigation");
		if (this.navigation == null)
			throw new LiferayElementNotFoundException();
	}

	@Override
	public void nodeAdded(DomChangeEvent event) {

		if (!inputValueAdded && event.getSource() instanceof HtmlTextInput) {
			HtmlTextInput textInput = (HtmlTextInput) event.getSource();
			if (navigation.compareDocumentPosition(textInput) != HtmlElement.DOCUMENT_POSITION_FOLLOWING
					&& navigation.compareDocumentPosition(textInput) != HtmlElement.DOCUMENT_POSITION_PRECEDING) {

				textInput.setValueAttribute(this.tabName);
				inputValueAdded = true;
			}
		} else if (event.getSource() instanceof HtmlButton) {
			HtmlButton button = (HtmlButton)event.getSource(); 
			if (button.getId().equalsIgnoreCase("save")){
				try {
					this.isJobEnded = true;
//					button.click();
				} catch (Exception e) {
					e.printStackTrace();
				}
				//page.removeDomChangeListener(this);
			}
		}
	}

	@Override
	public void nodeDeleted(DomChangeEvent arg0) {

	}

	public boolean isJobEnded() {
		return isJobEnded;
	}
}
